import hmac
import hashlib
import base64
import requests
import execjs

class CsdnCrawler():
    def __init__(self) -> None:
        self.tag_id=None
        self.x_ca_key = '203899271'
        self.x_ca_nonce = None
        self.app_secret = 'bK9jk5dBEtjauy6gXL7vZCPJ1fOy076H'
        pass
    
    def reqTagsJson(self,tag_id):
        self.tag_id = tag_id
        
        params = {
            'deviceType': 'PC',
            'tagId': tag_id,
        }
        headers = {
            'accept': 'application/json, text/plain, */*',
            'x-ca-key': self.x_ca_key,
            'x-ca-nonce': self.generateNonce(),
            'x-ca-signature': self.generateSignature(),
            'x-ca-signature-headers': 'x-ca-key,x-ca-nonce',
        }
        res = requests.get(
            f'https://bizapi.csdn.net/community-cloud/v1/homepage/community/by/tag',
            params=params,
            headers=headers
        )
        return res.json()
    
    def generateSignature(self):
        message =  f'GET\napplication/json, text/plain, */*\n\n\n\nx-ca-key:{self.x_ca_key}\nx-ca-nonce:{self.x_ca_nonce}\n/community-cloud/v1/homepage/community/by/tag?deviceType=PC&tagId={self.tag_id}'
        h = hmac.new(self.app_secret.encode('utf-8'),message.encode('utf-8'),hashlib.sha256).digest()
        signature = base64.b64encode(h).decode()
        return signature
 
    def generateNonce(self):
        ctx = execjs.compile('''
            f = function(e) {
                var t = e || null;
                return null == t && (t = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (function(e) {
                    var t = 16 * Math.random() | 0;
                    return ("x" === e ? t : 3 & t | 8).toString(16)
                }
                ))),
                t
            }
        ''')
        self.x_ca_nonce=ctx.call('f')
        return self.x_ca_nonce
 
 
 
tag_id = 6
csdnCrawler = CsdnCrawler()    
res = csdnCrawler.reqTagsJson(tag_id)
print(res['data'])
